package com.lc.app.myaccount.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lc.app.myaccount.entity.UserEntity;
import com.lc.app.myaccount.helper.DBOpenHelper;

/**
 * Created by LC on 2/5/2016.
 */
public class UserDao {
    private DBOpenHelper helper;
    private SQLiteDatabase db;

    public UserDao(Context context) {
        this.helper = new DBOpenHelper(context);
        db = helper.getWritableDatabase();
    }

    public void add(UserEntity user) {
        db.execSQL("insert into tb_user(name,password,isadmin) values(?,?,?)",user.toAddArray());
    }

    public void update(UserEntity user) {
        db.execSQL("update tb_user set name=?,password =?,isadmin=? where _id = ?",user.toUpdateArray());
    }

    public UserEntity find(int id) {
        Cursor cursor = db.rawQuery("select _id,name,password,isadmin from tb_user where _id = ? ",new String[]{String.valueOf(id)});
        if(cursor.moveToNext()){
            UserEntity user = new UserEntity();
            user.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            user.setName(cursor.getString(cursor.getColumnIndex("name")));
            user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
            user.setIsAdmin(cursor.getInt(cursor.getColumnIndex("isadmin")));
            return user;
        }else{
            return null;
        }
    }

    public UserEntity findByName(String name) {
        Cursor cursor = db.rawQuery("select _id,name,password,isadmin from tb_user where name = ? ",new String[]{name});
        if(cursor.moveToNext()){
            UserEntity user = new UserEntity();
            user.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            user.setName(cursor.getString(cursor.getColumnIndex("name")));
            user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
            user.setIsAdmin(cursor.getInt(cursor.getColumnIndex("isadmin")));
            return user;
        }else{
            return null;
        }
    }

    public UserEntity getCurrentUser(){
       Cursor cursor = db.rawQuery("select id,user from tb_current",new String[]{});
        if(cursor.moveToNext()){
            UserEntity user = new UserEntity();
            user.set_id(cursor.getInt(cursor.getColumnIndex("id")));
            user.setName(cursor.getString(cursor.getColumnIndex("user")));
            return user;
        }else{
            return null;
        }
    }

}
